window._RHM = {

    _MAINLABEL:null,

    _PAGESIZE:20,

    _PAGENMB:0,

    _YLPAGESIZE:20,

    _YLPAGENMB:0,

    _RESULTOBJ:null,

    _RESULTMSG:null,

    _SOURCEA:null,

    _SOURCEB:null,

    _SOURCEARR:null,

    _YLARR:null,

    _RACEMAP:null,

    _RACEARR:null,

    _INTRO:"角色融合规则:\n"+
            "1.界面左边的角色为主角色,右边为素材\n"+
            "2.主角色五维增长对应素材五维中最高的一条的10%,但不能超过主角色的10%\n"+
            "3.素材修为中评级最高的一条和主角色进行叠加\n"+
            "4.融合后五维达到一定阶段角色品质会升级\n"+
            "5.融合后如果修为\"完全符合\"某个角色的修为则主角色会转变为改角色\n"+
            "6.融合后如果出现角色转变则主角色会习得新角色的初始技能\n"+
            "7.只能选择同种族的两个角色进行融合,且融合后的角色也是该种族\n"+
            "8.每次融合消耗一个融合丹\n"+
            "9.仓库界面可以执行\"推荐融合\":按配方融合得到新的角色,此融合不会增加五维且仅限SS级以下的角色\n"+
            "10.角色到达SS级以后在仓库界面可以执行\"一键融合\":此操作只会增加五维不会增加修为",

    closeUi:function(){
        if(_RHM._MAINLABEL){
            _GRM.putNode(_RHM._MAINLABEL);
            _RHM._MAINLABEL = null;
        }
    },

    showUi:function(parentNode,param){

        var uiObj = _GRM.getNodeObj('ronghe');
        var mainLabel = uiObj.node;
        _RHM._MAINLABEL = mainLabel;
        _RHM._RESULTOBJ = null;
        _RHM._SOURCEA = null;
        _RHM._SOURCEB = null;
        _RHM._PAGENMB = 0;
        _RHM._YLPAGENMB = 0;

        if(uiObj.isnew){
            _RHM.initButton(mainLabel);
        }

        parentNode.addChild(mainLabel);

        _RHM.refreshAll();

        _RHM.getraceArr();

        return mainLabel;

    },

    getraceArr:function(){
        _RHM._RACEMAP={};
        _RHM._RACEARR=[];
        for(var i=0;i<window.gameData.playerTeamBack.length;i++){
            var npcrace = _NPC[window.gameData.playerTeamBack[i].npctype].race;
            if(!_RHM._RACEMAP[npcrace]){
                _RHM._RACEMAP[npcrace]=1;
                _RHM._RACEARR.push(npcrace);
            }
        }

    },

    zlbyrace:function(){

        _RHM._RACEARR.push(_RHM._RACEARR[0]);
        _RHM._RACEARR.splice(0,1);
        _RHM._RACEMAP={};
        for(var i=0;i<_RHM._RACEARR.length;i++){
            _RHM._RACEMAP[_RHM._RACEARR[i]]=i;
        }

        window.gameData.playerTeamBack.sort((a,b)=>{
            var brace = _NPC[b.npctype].race;
            var arace = _NPC[a.npctype].race;
            return _RHM._RACEMAP[brace]-_RHM._RACEMAP[arace];
        });

        _RHM._RESULTOBJ = null;
        _RHM._SOURCEA = null;
        _RHM._SOURCEB = null;
        _RHM._PAGENMB = 0;
        _RHM._YLPAGENMB = 0;
        _RHM.refreshAll();

    },

    initButton:function(mainLabel){
        var yulanlabel = _RHM._MAINLABEL.getChildByName('suomin');
        var yulanmaskLabel = _RHM._MAINLABEL.getChildByName('suomin').getChildByName('mask');
        yulanmaskLabel.on(cc.Node.EventType.TOUCH_START, function(){
            this.active = false;
        }, yulanlabel);

        var maskNode = mainLabel.getChildByName('mask');
        maskNode.on(cc.Node.EventType.TOUCH_START, function(){
            _RHM.closeUi();
        }, maskNode);

        var teamNodes = mainLabel.getChildByName('rightLabel')
                                 .getChildByName('background')
                                 .getChildByName('goods')
                                 .getChildren();
        for(var i=0;i<teamNodes.length;i++){
            teamNodes[i].teamIndex = i;
            teamNodes[i].on(cc.Node.EventType.TOUCH_START, function(){
                console.log(this.teamIndex);
                _RHM.selectRole(this.teamRole);
            }, teamNodes[i]);
        }


        var posANode = mainLabel.getChildByName('leftLabel')
                                .getChildByName('troops')
                                .getChildByName('posA');
        var posBNode = mainLabel.getChildByName('leftLabel')
                                .getChildByName('troops')
                                .getChildByName('posB');
        var btnUp = mainLabel.getChildByName('leftLabel')
                                .getChildByName('troops')
                                .getChildByName('buttonUp');
        var btnConfirm = mainLabel.getChildByName('leftLabel')
                                .getChildByName('troops')
                                .getChildByName('buttonConfirm');
        
        var buttonPre = mainLabel.getChildByName('leftLabel')
                                .getChildByName('troops')
                                .getChildByName('buttonPre');
        
        buttonPre.on(cc.Node.EventType.TOUCH_START, function(){
            _RHM.showYL();
        }, mainLabel);

        posANode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('A');
            _RHM._SOURCEA=null;
            _RHM._RESULTOBJ=null;
            _RHM.refreshRight();
            _RHM.refreshResult();
        }, posANode);
        posBNode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('B');
            _RHM._SOURCEB=null;
            _RHM._RESULTOBJ=null;
            _RHM.refreshRight();
            _RHM.refreshResult();
        }, posBNode);
        btnUp.on(cc.Node.EventType.TOUCH_START, function(){
            _RHM.ronghe();
        }, btnUp);
        btnConfirm.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('确认');
            _RHM.getronghe();
        }, btnConfirm);


        var btnClose = mainLabel.getChildByName('rightLabel')
                                .getChildByName('btn')
                                .getChildByName('close');
        var btnTips = mainLabel.getChildByName('rightLabel')
                                .getChildByName('btn')
                                .getChildByName('sxyn');
        var btnZl = mainLabel.getChildByName('rightLabel')
                                .getChildByName('btn')
                                .getChildByName('zl');
        btnZl.on(cc.Node.EventType.TOUCH_START, function(){
                                    _RHM.zlbyrace();
                                }, btnClose);
        btnClose.on(cc.Node.EventType.TOUCH_START, function(){
                                    //console.log('关闭');
                                    _RHM.closeUi();
                                }, btnClose);
        btnTips.on(cc.Node.EventType.TOUCH_START, function(){
                                    //console.log('说明');
                                    _TIPS.showMessage(_RHM._INTRO);
                                }, btnTips);


        var pageNode = mainLabel.getChildByName('rightLabel')
                                .getChildByName('background')
                                .getChildByName('page');
        var btnFirstNode = pageNode.getChildByName('first');
        var btnTailNode = pageNode.getChildByName('tail');
        var btnNextNode = pageNode.getChildByName('btnRight');
        var btnlastNode = pageNode.getChildByName('btnLeft');
        btnFirstNode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('首页');
            _RHM._PAGENMB=0;
            _RHM.refreshLeft();
        }, btnFirstNode);
        btnTailNode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('尾页');
            if(window.gameData.playerTeamBack.length%_RHM._PAGESIZE>0)
                _RHM._PAGENMB=Math.floor(window.gameData.playerTeamBack.length/_RHM._PAGESIZE);
            else
                _RHM._PAGENMB=Math.floor(window.gameData.playerTeamBack.length/_RHM._PAGESIZE)-1;
            if(_RHM._PAGENMB<0){
                _RHM._PAGENMB=0;
            }
            _RHM.refreshLeft();
        }, btnTailNode);
        btnNextNode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('下一页');
            _RHM._PAGENMB++;
            _RHM.refreshLeft();
        }, btnNextNode);
        btnlastNode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('上一页');
            if(_RHM._PAGENMB>0){
                _RHM._PAGENMB--;
                _RHM.refreshLeft();
            }
        }, btnlastNode);


        var YLbtnNextNode = yulanlabel.getChildByName('rightLabel')
                                    .getChildByName('background')
                                    .getChildByName('page')
                                    .getChildByName('btnRight');
        var YLbtnlastNode = yulanlabel.getChildByName('rightLabel')
                                    .getChildByName('background')
                                    .getChildByName('page')
                                    .getChildByName('btnLeft');
        YLbtnNextNode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('下一页');
            _RHM._YLPAGENMB++;
            _RHM.refreshYlRight();
        }, YLbtnNextNode);
        YLbtnlastNode.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('上一页');
            if(_RHM._YLPAGENMB>0){
                _RHM._YLPAGENMB--;
                _RHM.refreshYlRight();
            }
        }, YLbtnlastNode);
    },

    refreshAll:function(){
        _RHM.refreshLeft();
        _RHM.refreshRight();
        _RHM.refreshResult();
    },

    getSource:function(){

        var startIndex = _RHM._PAGENMB*_RHM._PAGESIZE;
        var endIndex = startIndex+_RHM._PAGESIZE;
        _RHM._SOURCEARR = [];
        for(var i=startIndex;i<endIndex;i++){
            _RHM._SOURCEARR.push({role:window.gameData.playerTeamBack[i],roleindex:i});
        }

    },

    getEnableNpc:function(sourceNpctype,xwlevelobj){
        var arr = [];
        var configA = _NPC[sourceNpctype];
        var race = configA.race;
        for(var key in _NPC){
            if(
                _NPC[key].race==race
                &&_RHM.isXwEnogh(_NPC[key].npcxw,xwlevelobj)
            ){
                arr.push(key);
            }
        }
        return arr;
    },

    showYL:function(){
        if(_RHM._SOURCEA==null||_RHM._SOURCEB==null){
            _TIPS.showMessage('请先选择素材');
            return;
        }
        var yulanLabel = _RHM._MAINLABEL.getChildByName('suomin');
        yulanLabel.active = true;
        var xwNodeArr = yulanLabel.getChildByName('leftLabel')
                        .getChildByName('troops')
                        .getChildByName('scrollview')
                        .getChildByName('view')
                        .getChildByName('content')
                        .getChildren();
        

        var sourceA = _RHM._SOURCEA.role;
        var sourceB = _RHM._SOURCEB.role;
        var xwlevel = _RHM.getXWLevel(sourceA,sourceB);
        var xwlevelobj = xwlevel.xwlevelObj;
        var sourceObj = xwlevel.sourceObj;

        _RHM._YLARR = _RHM.getEnableNpc(sourceA.npctype,xwlevelobj);

        console.log(xwlevelobj,sourceObj,_RHM._YLARR);

        for(var i=0;i<xwNodeArr.length;i++){
            xwNodeArr[i].getChildByName('name')
            .getComponent(cc.Label).string = "";
        }
        var xwindex = 0;
        for(var key in sourceObj){
            var msg = _XW[key].label+":"+sourceObj[key];
            xwNodeArr[xwindex].getChildByName('name')
            .getComponent(cc.Label).string = msg;
            xwindex++;
        }

       
        _RHM.refreshYlRight();
    },

    refreshYlRight:function(){
        var yulanLabel = _RHM._MAINLABEL.getChildByName('suomin');
        var roleNodeArr = yulanLabel.getChildByName('rightLabel')
                        .getChildByName('background')
                        .getChildByName('goods').getChildren();
         var roleindex = _RHM._YLPAGENMB*_RHM._YLPAGESIZE;
         
         for(var i=0;i<roleNodeArr.length;i++){
            var rolenode = roleNodeArr[i];
            if(_RHM._YLARR[roleindex]){
                _RHM.refreshYLLeftOne(rolenode,_RHM._YLARR[i]);
            }else{
                rolenode.active = false;
            }
            roleindex++;
        }
    },

    refreshLeft:function(){
        _RHM.getSource();
        _RHM._MAINLABEL.getChildByName('rightLabel')
                                 .getChildByName('background')
                                 .getChildByName('page')
                                 .getChildByName('label')
                                 .getComponent(cc.Label).string = _RHM._PAGENMB+1;
        var teamNodes = _RHM._MAINLABEL.getChildByName('rightLabel')
                                 .getChildByName('background')
                                 .getChildByName('goods')
                                 .getChildren();
        for(var i=0;i<teamNodes.length;i++){
            if(_RHM._SOURCEARR[i]){
                teamNodes[i].teamRole = _RHM._SOURCEARR[i];
                _RHM.refreshLeftOne(teamNodes[i],teamNodes[i].teamRole.role);
            }else{
                teamNodes[i].teamRole = null;
                teamNodes[i].active = false;
            }
        }
    },

    refreshLeftOne:function(node,roleInfo){

        if(roleInfo){

            var npctype = roleInfo.npctype;
            var npctypeConfig = _NPC[npctype];
            var npcjob = npctypeConfig.job;
            var npcrace = npctypeConfig.race;
            var npcqua = npctypeConfig.level;

            node.active = true;

            var roleData = _ROLEDATA.getRoleDataOfPlayer(roleInfo);
            var lv = roleData.lv;

            var faceNode = node.getChildByName('touxian');
            var nameNode = node.getChildByName('name');
            var lvNode = node.getChildByName('lv');
            var ftypeNode = node.getChildByName('ftype');
            var ftypeStrNode = ftypeNode.getChildByName('ftypeStr');

            var jobNode = node.getChildByName('job');
            var jobStrNode = jobNode.getChildByName('ftypeStr');
            jobNode.color = new cc.color(window._JOB[npcjob].color);
            jobStrNode.getComponent(cc.Label).string = window._JOB[npcjob].sname;
            var zhongNode = node.getChildByName('zhong');
            var zhongStrNode = zhongNode.getChildByName('ftypeStr');
            zhongNode.color = new cc.color(window._RACE[npcrace].color);
            zhongStrNode.getComponent(cc.Label).string = window._RACE[npcrace].name;
            var quaNode = node.getChildByName('qua');
            var quaStrNode = quaNode.getChildByName('ftypeStr');
            quaNode.color = new cc.color(window._CS.qua[npcqua].color);
            quaStrNode.getComponent(cc.Label).string = npcqua;

            faceNode.getComponent(cc.Sprite).spriteFrame = _GRM.getFaceFrame(roleInfo.face);
            nameNode.getComponent(cc.Label).string = roleInfo.name;
            lvNode.getComponent(cc.Label).string = "LV."+lv;
            ftypeNode.color = new cc.color(_CS.ftype[roleInfo.ftype].color);
            ftypeStrNode.getComponent(cc.Label).string = roleInfo.ftype;


        }else{

            node.active = false;

        }
        
    },

    refreshYLLeftOne:function(node,npctype){
        var npctypeConfig = _NPC[npctype];
        if(npctypeConfig){

            var npcjob = npctypeConfig.job;
            var npcrace = npctypeConfig.race;
            var npcqua = npctypeConfig.level;

            node.active = true;

            var faceNode = node.getChildByName('touxian');
            var nameNode = node.getChildByName('name');
            var ftypeNode = node.getChildByName('ftype');
            var ftypeStrNode = ftypeNode.getChildByName('ftypeStr');

            var jobNode = node.getChildByName('job');
            var jobStrNode = jobNode.getChildByName('ftypeStr');
            jobNode.color = new cc.color(window._JOB[npcjob].color);
            jobStrNode.getComponent(cc.Label).string = window._JOB[npcjob].sname;
            var zhongNode = node.getChildByName('zhong');
            var zhongStrNode = zhongNode.getChildByName('ftypeStr');
            zhongNode.color = new cc.color(window._RACE[npcrace].color);
            zhongStrNode.getComponent(cc.Label).string = window._RACE[npcrace].name;
            var quaNode = node.getChildByName('qua');
            var quaStrNode = quaNode.getChildByName('ftypeStr');
            quaNode.color = new cc.color(window._CS.qua[npcqua].color);
            quaStrNode.getComponent(cc.Label).string = npcqua;

            faceNode.getComponent(cc.Sprite).spriteFrame = _GRM.getFaceFrame(npctypeConfig.face);
            nameNode.getComponent(cc.Label).string = npctype;
            ftypeNode.color = new cc.color(_CS.ftype[npctypeConfig.ftype].color);
            ftypeStrNode.getComponent(cc.Label).string = npctypeConfig.ftype;


        }else{

            node.active = false;

        }
        
    },

    selectRole:function(role){
      
        if(_RHM._SOURCEA == null){
            if(_RHM._SOURCEB!=null){
                if(
                    _NPC[role.role.npctype].race!=_NPC[_RHM._SOURCEB.role.npctype].race
                    &&_NPC[role.role.npctype].race!='mo'
                    &&_NPC[_RHM._SOURCEB.role.npctype].race!='mo'
                ){
                    _TIPS.showMessage('融合素材需要种族相同');
                    return;
                }
            }   
            _RHM._SOURCEA = role;
            _RHM.refreshRight();
        }else if(_RHM._SOURCEB == null){
            if(_RHM._SOURCEA!=null){
                if(
                    _NPC[role.role.npctype].race!=_NPC[_RHM._SOURCEA.role.npctype].race
                    &&_NPC[role.role.npctype].race!='mo'
                    &&_NPC[_RHM._SOURCEA.role.npctype].race!='mo'
                ){
                    _TIPS.showMessage('融合素材需要种族相同');
                    return;
                }
            }
            _RHM._SOURCEB = role;
            _RHM.refreshRight();
        }

    },

    refreshRight:function(){

        var posANode = _RHM._MAINLABEL.getChildByName('leftLabel')
                        .getChildByName('troops')
                        .getChildByName('posA');
        var posBNode = _RHM._MAINLABEL.getChildByName('leftLabel')
                        .getChildByName('troops')
                        .getChildByName('posB');
        
        if(!_RHM._SOURCEA){
            posANode.active = false;
        }else{
            _RHM.refreshLeftOne(posANode,_RHM._SOURCEA.role);
        }

        if(!_RHM._SOURCEB){
            posBNode.active = false;
        }else{
            _RHM.refreshLeftOne(posBNode,_RHM._SOURCEB.role);
        }

    },

    refreshResult:function(){

        var resultNode = _RHM._MAINLABEL.getChildByName('leftLabel')
                                        .getChildByName('result');

        if(!_RHM._RESULTOBJ){
            resultNode.active = false;
        }else{
            resultNode.active = true;
            var roleInfo = _RHM._RESULTOBJ;
            var npctype = roleInfo.npctype;
            var npctypeConfig = _NPC[npctype];
            var npcjob = npctypeConfig.job;
            var npcrace = npctypeConfig.race;
            //var npcqua = npctypeConfig.level;
            var npcqua = _ROLEDATA.getRoleQua(roleInfo);
            var roleData = _ROLEDATA.getRoleDataOfPlayer(roleInfo);
            var lv = roleData.lv;
            

            var backgroundNode = resultNode.getChildByName('background');
            var node = backgroundNode.getChildByName('pos');
            var fivenode = backgroundNode.getChildByName('five').getChildByName('five');
            var resultLabel=backgroundNode.getChildByName('resultMsg');

            
            var faceNode = node.getChildByName('touxian');
            var nameNode = node.getChildByName('name');
            var lvNode = node.getChildByName('lv');
            var ftypeNode = node.getChildByName('ftype');
            var ftypeStrNode = ftypeNode.getChildByName('ftypeStr');

            var jobNode = node.getChildByName('job');
            var jobStrNode = jobNode.getChildByName('ftypeStr');
            jobNode.color = new cc.color(window._JOB[npcjob].color);
            jobStrNode.getComponent(cc.Label).string = window._JOB[npcjob].sname;
            var zhongNode = node.getChildByName('zhong');
            var zhongStrNode = zhongNode.getChildByName('ftypeStr');
            zhongNode.color = new cc.color(window._RACE[npcrace].color);
            zhongStrNode.getComponent(cc.Label).string = window._RACE[npcrace].name;
            var quaNode = node.getChildByName('qua');
            var quaStrNode = quaNode.getChildByName('ftypeStr');
            quaNode.color = new cc.color(window._CS.qua[npcqua].color);
            quaStrNode.getComponent(cc.Label).string = npcqua;

            faceNode.getComponent(cc.Sprite).spriteFrame = _GRM.getFaceFrame(roleInfo.face);
            nameNode.getComponent(cc.Label).string = roleInfo.npctype;
            lvNode.getComponent(cc.Label).string = "LV."+lv;
            ftypeNode.color = new cc.color(_CS.ftype[roleInfo.ftype].color);
            ftypeStrNode.getComponent(cc.Label).string = roleInfo.ftype;


            _RHM.drawSix(fivenode.getChildByName('attr'),
                    fivenode.getChildByName('data').getComponent(cc.Graphics)
                    ,[roleInfo.plv,roleInfo.dlv,roleInfo.ilv,roleInfo.mlv,roleInfo.hlv]);

            if(_RHM._RESULTMSG&&_RHM._RESULTMSG.length>0){
                var msg = "";
                for(var i=0;i<_RHM._RESULTMSG.length;i++){
                    var msgobj = _RHM._RESULTMSG[i];
                    if(msgobj!=null){
                        if(msgobj.type=="npc"&&msgobj.old!=msgobj.new){
                            msg+=msgobj.old+" -> "+msgobj.new+"\n";
                        }else if(msgobj.type=="attr"){
                            msg+=_CS.fivedataStr[msgobj.attr]+":"+msgobj.old+" -> "+msgobj.new+"\n";
                        }else if(msgobj.type=="xw"){
                            if(msgobj.old!=null&&msgobj.new!=null&&msgobj.old!=msgobj.new){
                                msg+=_XW[msgobj.attr].label+":"+msgobj.old+" -> "+msgobj.new+"\n";
                            }else if(msgobj.old==null&&msgobj.new!=null){
                                msg+="新增"+_XW[msgobj.attr].label+":"+msgobj.new+"\n";
                            }
                        }
                    }
                }
                resultLabel.getComponent(cc.Label).string = msg;
            }else{
                resultLabel.getComponent(cc.Label).string = "毫无变化!";
            }
            
            /*
             var xwArr = backgroundNode.getChildByName('content').getChildren();
            var xwindex = 0;
            for(var i=0;i<xwArr.length;i++){
                xwArr[i].active = false;
            }
            var xwlevelA = _ROLEDATA.getRoleXwLevel(roleInfo);
            for(var key in xwlevelA){
                xwArr[xwindex].getChildByName('name').getComponent(cc.Label).string = _XW[key].label;
                xwArr[xwindex].getChildByName('xwdata').getComponent(cc.Label).string = "";
                xwArr[xwindex].getChildByName('czdata').getComponent(cc.Label).string = xwlevelA[key];
                xwArr[xwindex].getChildByName('img_lock').active = npctypeConfig.npcxw[key]?true:false;
                xwArr[xwindex].active = true;
                xwindex++;
            }*/
        }
    },

    //画六维图，并填充
	drawSix(attrNodes,graphics,dataArr) {

        attrNodes.getChildByName('plv').getComponent(cc.Label).string='武:'+dataArr[0];
        attrNodes.getChildByName('plv').color = new cc.color(_CS.attrColor['attack'])
        attrNodes.getChildByName('dlv').getComponent(cc.Label).string='统:'+dataArr[1];
        attrNodes.getChildByName('dlv').color = new cc.color(_CS.attrColor['defend'])
        attrNodes.getChildByName('ilv').getComponent(cc.Label).string='智:'+dataArr[2];
        attrNodes.getChildByName('ilv').color = new cc.color(_CS.attrColor['mattack'])
        attrNodes.getChildByName('mlv').getComponent(cc.Label).string='德:'+dataArr[3];
        attrNodes.getChildByName('mlv').color = new cc.color(_CS.attrColor['mdefend'])
        attrNodes.getChildByName('hlv').getComponent(cc.Label).string='体:'+dataArr[4];
        attrNodes.getChildByName('hlv').color = new cc.color(_CS.attrColor['maxHp'])

        var per = _MRDL.paramLength/_MRDL.maxlength;
        _CU.drawData(graphics,dataArr,per);
      
	},


    getMaxXwObj:function(targetxw){
        var maxxwname=null;
        var maxxwlevel = null;
        var hasSame = false;
        for(var key in targetxw){
            if(maxxwlevel==null){
                maxxwname=key;
                maxxwlevel=targetxw[key];
            }else{
                if(_RHM.comparaLevel(targetxw[key],maxxwlevel)){
                    hasSame=false;
                    maxxwname=key;
                    maxxwlevel=targetxw[key];
                }else{
                    if(targetxw[key]==maxxwlevel){
                        hasSame=true;
                    }
                }
            }
        }

        if(!hasSame&&maxxwname&&maxxwlevel){
            return {xw:maxxwname,level:maxxwlevel};
        }else{
            //最高修为不止一条 视为没有融合修为
            return null;
        }
    },

    getRhXw:function(sourceA,sourceB,result){

        var reslutMsg = {type:'xw',attr:null,old:null,new:null};

        result.xw = _CU.cloneObj(sourceA.xw);

        if(!sourceA.xwlevel){
            result.xwlevel=_CU.cloneObj(_NPC[sourceA.npctype].npcxw);
        }else{
            result.xwlevel=_CU.cloneObj(sourceA.xwlevel);
        }

        var targetxw = sourceB.xwlevel;
        if(!targetxw){
            if(_NPC[sourceB.npctype]){
                targetxw=_NPC[sourceB.npctype].npcxw;
            }
        }

        var maxxwObj = _RHM.getMaxXwObj(targetxw);

        if(maxxwObj==null){
            return null;
        }

        var maxxwname=maxxwObj.xw;
        var maxxwlevel = maxxwObj.level;

        reslutMsg.attr = maxxwname;
        reslutMsg.old = result.xwlevel[maxxwname];

        if(!result.xwlevel[maxxwname]){
            result.xwlevel[maxxwname]=maxxwlevel;
        }else{
            if(_RHM.comparaLevel(maxxwlevel,result.xwlevel[maxxwname])){
                result.xwlevel[maxxwname]=maxxwlevel;
            }else if(maxxwlevel==result.xwlevel[maxxwname]){
                result.xwlevel[maxxwname]=_RHM.getNextLevel(result.xwlevel[maxxwname]);
            }
        }

        reslutMsg.new = result.xwlevel[maxxwname];

        for(var key in result.xwlevel){
            if(sourceA.xw[key]){
                result.xw[key]=sourceA.xw[key];
            }else{
                result.xw[key]=0;
            }
        }

        return reslutMsg;

    },

    getRhAttr:function(sourceA,sourceB,result){

        var reslutMsg = {type:'attr',attr:null,old:null,new:null};
        var arr = [];
        arr.push({type:"hlv",value:sourceB.hlv});
        arr.push({type:"ilv",value:sourceB.ilv});
        arr.push({type:"dlv",value:sourceB.dlv});
        arr.push({type:"mlv",value:sourceB.mlv});
        arr.push({type:"plv",value:sourceB.plv});

        arr.sort((a,b)=>{
            return b.value-a.value;
        });

        //console.log(arr);

        var targetattrObj = arr[0];
        var targetattr=targetattrObj.type;
        var realadd = targetattrObj.value/10;
        var old = sourceA[targetattr]/10;
        if(realadd>old){
            realadd=old;
        }

        reslutMsg.attr = targetattr;
        reslutMsg.old = sourceA[targetattr];

        reslutMsg.new = sourceA[targetattr]+Math.floor(realadd);

        result.hlv = sourceA.hlv;
        result.ilv = sourceA.ilv;
        result.dlv = sourceA.dlv;
        result.mlv = sourceA.mlv;
        result.plv = sourceA.plv;

        result[targetattr]=reslutMsg.new;

        return reslutMsg;
    },

    isXwEqual:function(xwa,xwb){
        for(var key in xwa){
            if(xwb[key]!=xwa[key]){
                return false;
            }
        }

        for(var key in xwb){
            if(xwb[key]!=xwa[key]){
                return false;
            }
        }

        return true;
    },

    getRhNpc:function(sourceA,result){

        var sourceNpc = sourceA.npctype;
        var sourceRace = _NPC[sourceNpc]?_NPC[sourceNpc].race:null;
        result.npctype = sourceNpc;
        for(var key in _NPC){
            var tempconf = _NPC[key];
            if(key!=sourceNpc
                &&tempconf.race==sourceRace
                &&_RHM.isXwEqual(tempconf.npcxw,result.xwlevel)
            ){
                result.npctype=key;
                break;
            }
        }

        var reslutMsg = {type:'npc',attr:null,old:sourceNpc,new:result.npctype};
        
        return reslutMsg;
    },

    getRhNpcSkill:function(result){

        var skills = _NPC[result.npctype]?_NPC[result.npctype].skill:null;
        if(skills&&skills.length>0){
            for(var i=0;i<skills.length;i++){
                if(!_CU.isContain(result.skill,skills[i])){
                    result.skill.push(skills[i]);
                }
            }
        }

    },

    ronghe:function(){
        //console.log('融合',_RHM._SOURCEA,_RHM._SOURCEB);
        if(_RHM._SOURCEA==null||_RHM._SOURCEB==null){
            _TIPS.showMessage('请先选择素材');
            return;
        }

        if(_RHM._SOURCEA.roleindex == _RHM._SOURCEB.roleindex){
            _TIPS.showMessage('不可重复选择素材');
            return;
        }

        //构造新角色
        var sourceA = _RHM._SOURCEA.role;
        var sourceB = _RHM._SOURCEB.role;
        var result = {equip:[],skill:[],name:sourceA.name,mg:0,hp:0,exp:sourceA.exp,xw:{}};
        var resultMsg = [];
        
        //获取素材五维中最高一条的1/10
        resultMsg.push(_RHM.getRhAttr(sourceA,sourceB,result));

        //获取素材修为中最高一条并叠加
        resultMsg.push(_RHM.getRhXw(sourceA,sourceB,result));

        //根据融合结果判断是否需要转变角色并获取技能
        resultMsg.push(_RHM.getRhNpc(sourceA,result));

       //获取新角色类型
        var newnpctype = result.npctype;
        var npcconfig = _NPC[newnpctype];

        result.skill = _CU.cloneObj(sourceA.skill);

        if(sourceA.npctype!=result.npctype){
            _RHM.getRhNpcSkill(result);
        }

        result.face = npcconfig.face;
        result.ftype = npcconfig.ftype;             
        result.pf = npcconfig.pf;
        result.npctype = newnpctype;

        _RHM._RESULTOBJ = result;
        _RHM._RESULTMSG = resultMsg;

        console.log('融合结果:',_RHM._RESULTOBJ,resultMsg);

        _RHM.refreshResult();
    },

    //根据随机出的npc和混合修为 随机出融合修为
    getNpcXw:function(npcxwlevelobj,npc){
        var nexXwObj = {};
        var xwlevelObj = {};
        var xwnmb = 0;
        var npcconfig = _NPC[npc];
        for(var xw in npcconfig.npcxw){
            xwnmb++;
            nexXwObj[xw]=0;
            xwlevelObj[xw]=npcxwlevelobj[xw];
        }

        if(xwnmb<9){
            var leftnmb = 9-xwnmb;
            var temarr = [];
            for(var xw in npcxwlevelobj){
                if(!nexXwObj[xw]&&nexXwObj[xw]!=0){
                    temarr.push(xw);
                }
            }

           for(var i=0;i<leftnmb;i++){
                if(temarr.length>0){
                    var randomindex = Math.floor(Math.random()*temarr.length);
                    var randomxw = temarr[randomindex];
                    nexXwObj[randomxw]=0;
                    xwlevelObj[randomxw]=npcxwlevelobj[randomxw];
                    console.log('随机附加修为:',xw,npcxwlevelobj[randomxw]);
                    temarr.splice(randomindex,1);
                }
           }
        }

        console.log('融合结果:',npcxwlevelobj,npc,nexXwObj,xwlevelObj);

        return {xw:nexXwObj,xwlevel:xwlevelObj};
    },

    getXWLevel:function(npca,npcb){
        var xwlevelA = _ROLEDATA.getRoleXwLevel(npca);
        var xwlevelB = _ROLEDATA.getRoleXwLevel(npcb);
        var xwlevelObj={};
        var sourceObj = {};
        for(var key in xwlevelA){
            xwlevelObj[key]=xwlevelA[key];
            sourceObj[key]=xwlevelA[key];
        }
        for(var key in xwlevelB){
            if(!xwlevelObj[key]){
                xwlevelObj[key]=xwlevelB[key];
                sourceObj[key]=xwlevelB[key];
            }else{
                if(xwlevelObj[key]!=xwlevelB[key]){
                    xwlevelObj[key]=_RHM.getMaxLevel(xwlevelObj[key],xwlevelB[key]);
                    sourceObj[key]=xwlevelObj[key];
                }else{
                    xwlevelObj[key]=_RHM.getNextLevel(xwlevelObj[key]);
                    sourceObj[key]=sourceObj[key]+"+"+sourceObj[key]+"="+xwlevelObj[key];
                }
            }
        }
        return {xwlevelObj:xwlevelObj,sourceObj:sourceObj};
    },

    getNpcTypeArr:function(sourceA,npcxwlevelobj){
        var configA = _NPC[sourceA.npctype];
        var race = configA.race;
        var randomArr = [];
        for(var key in _NPC){
            if(
                _NPC[key].race==race
                &&_RHM.isXwEnogh(_NPC[key].npcxw,npcxwlevelobj)
            ){
                randomArr.push(key);
            }
        }
        return randomArr;
    },

    getNpcType:function(sourceA,npcxwlevelobj){
       

        var randomArr = _RHM.getNpcTypeArr(sourceA,npcxwlevelobj);
        //console.log('可选融合角色',randomArr);
        if(randomArr&&randomArr.length>0){
            return _CU.randomObj(randomArr);
        }

        return sourceA.npctype;
    },

    isXwEnogh:function(source,target){

        if(!source){
            return false;
        }

        for(var key in source){
            if(!target[key]){
                return false;
            }
            if(_RHM.comparaLevel(source[key],target[key])){
                return false;
            }
        }

        return true;
    },

    getronghe:function(){
        if(_RHM._SOURCEA==null||_RHM._SOURCEB==null){
            _TIPS.showMessage('请先选择素材');
            return;
        }

        if(_RHM._RESULTOBJ==null){
            return ;
        }

        if(!_GAMEDATAHELPER.reduceItemByName('融合丹')){
            _TIPS.showMessage('融合丹不足无法融合');
            return false;
        }

        var aindex = _RHM._SOURCEA.roleindex;
        var bindex = _RHM._SOURCEB.roleindex;
        if(aindex>bindex){
            window.gameData.playerTeamBack.splice(aindex,1);
            window.gameData.playerTeamBack.splice(bindex,1);
        }else{
            window.gameData.playerTeamBack.splice(bindex,1);
            window.gameData.playerTeamBack.splice(aindex,1);
        }

        _RHM.dropEquipOfRole(_RHM._SOURCEA.role);
        _RHM.dropEquipOfRole(_RHM._SOURCEB.role);

        _ROLEDATA.resetRoleQua(_RHM._RESULTOBJ)
        window.gameData.playerTeamBack.unshift(_RHM._RESULTOBJ);

        //点亮图鉴
        _GAMEDATAHELPER.signNpcTj(_RHM._RESULTOBJ.npctype);

        _RHM._RESULTOBJ=null;
        _RHM._SOURCEA=null;
        _RHM._SOURCEB=null;
        _RHM.refreshAll();

        _TIPS.showMessage('融合成功请前往替补队伍查看,原角色的装备已经放入仓库');

    },

    dropEquipOfRole:function(role){
        if(role&&role.equip&&role.equip.length>0){
            for(var i=0;i<role.equip.length;i++){
                window.gameData.equipItem.unshift(role.equip[i]);
            }
        }
    },

    getExtraAttr:function(data){
        return Math.floor(data/50);
    },

    getMax:function(a, b) {
        if(a >= b) {
          return a+_RHM.getExtraAttr(b);
        } else {
          return b+_RHM.getExtraAttr(a);
        }
    },

    comparaLevel:function(lvA,lvB){
        if(!_CS.qua[lvA]){
            return false;
        }
        if(!_CS.qua[lvB]){
            return true;
        }
        return _CS.qua[lvA].val>_CS.qua[lvB].val;
    },

    getMaxLevel:function(lvA,lvB){
        return _CS.qua[lvA].val>_CS.qua[lvB].val?lvA:lvB;
    },

    getNextLevel:function(level){
        if(level=="SS"){
            return level;
        }else if(level=="S"){
            return "SS";
        }else if(level=="A"){
            return "S";
        }else if(level=="B"){
            return "A";
        }else if(level=="C"){
            return "B";
        }else if(level=="D"){
            return "C";
        }
    },

    getTestStr:function(arr){
        var str = "[";
        for(var i=0;i<arr.length;i++){
            str+=arr[i]+"("+_NPC[arr[i]].level+"),"
        }
        return str+"]";
    },


    getLevelToNmb:function(level){
        if(level=="SS"){
            return 6;
        }else if(level=="S"){
            return 5;
        }else if(level=="A"){
            return 4;
        }else if(level=="B"){
            return 3;
        }else if(level=="C"){
            return 2;
        }else if(level=="D"){
            return 1;
        }
        return 0;
    },

    //xwb是否满足xwa
    xwEnable:function(xwa,xwb,xwc){

        for(var key in xwa){
            if(!xwb[key]){
                if(xwc[key]!=xwa[key])
                    return false;
            }
        }

        return true;

    },

    //计算实际融合次数
    getRealRhNmb:function(nmb){

        if(nmb%2==0&&nmb>0){
            var tnmb = Math.floor(nmb/2);
            return _RHM.getRealRhNmb(tnmb)+tnmb;
        }

        return 0;

    },

    //计算融合次数 var rhnmb = _RHM.getRhNmb({qiang:'SS'},{qiang:'A'},{qiang:'C'});
    getRhNmb:function(targetxw,npcxw,tjmap,target){

        var rhnmb = 0;
        var zgnmb = 0;
        var rhmap = {};

        for(var xw in targetxw){

            var targetlevel = targetxw[xw];
            var npclevel = npcxw[xw];

            if(
                (tjmap[xw]&&tjmap[xw].npc!=target)
                ||(npcxw[xw]&& _RHM.getLevelToNmb(targetlevel)<=_RHM.getLevelToNmb(npclevel))
            ){
                
                
                var tjlevel = tjmap[xw]?tjmap[xw].lv:null;
                var tjnpc = tjmap[xw]?tjmap[xw].npc:null;

                rhmap[xw]=[targetlevel,npclevel];

                var targetnmb = _RHM.getLevelToNmb(targetlevel);
                var npcnmb = _RHM.getLevelToNmb(npclevel);
                var tjnmb = _RHM.getLevelToNmb(tjlevel);
                var tnmb = 0;//需要抓怪个数
                var sjrhnmb = 0;//实际融合个数

                if(npcnmb<targetnmb){
                    if(npcnmb<tjnmb){
                        if(tjnmb>=targetnmb){
                            tnmb=1;
                            sjrhnmb=1;
                        }else{
                            tnmb = Math.pow(2, (targetnmb-tjnmb));
                            sjrhnmb = _RHM.getRealRhNmb(tnmb);
                        }
                    }else if(npcnmb==tjnmb){
                        tnmb=Math.pow(2, (targetnmb-tjnmb))-1;
                        sjrhnmb = _RHM.getRealRhNmb(tnmb+1);
                    }else{
                        var tempnmb = Math.pow(2, (targetnmb-npcnmb));
                        tnmb=(tempnmb-1)*Math.pow(2, (npcnmb-tjnmb));
                        sjrhnmb = _RHM.getRealRhNmb(tempnmb)+_RHM.getRealRhNmb(tnmb)
                    }
                }

                rhnmb+=sjrhnmb;
                zgnmb+=tnmb;
                if(tnmb>0)
                rhmap[xw].push({lv:tjlevel,npc:tjnpc,nmb:tnmb});


            }else{

                return null;

            }

            

        }

        console.log("抓怪:"+zgnmb,"融合:"+rhnmb,rhmap);
        return {rhnmb:rhnmb,detail:rhmap};

    },

    //_RHM.getTjrhByNpc('yao',A,{qiang:'A'},{qiang:{lv:'D',npc:'山贼'},'bq':{lv:'D',npc:'渔夫'}})
    getTjrhByNpc:function(race,level,npcxw,tjmap){

        var levelnmb = _RHM.getLevelToNmb(level);
        var resultrhnmb = -1;//推荐融合次数
        //var resultrhzl = 0;//推荐融合战力
        var resultRole = null;
        var resultDetail = null;
        var result = [];

        for(var key in _NPC){
            var npcconf = _NPC[key];
            var npclevelnmb = _RHM.getLevelToNmb(npcconf.level);
            if(
               npcconf.race==race
               &&npclevelnmb>levelnmb
               &&_RHM.xwEnable(npcconf.npcxw,tjmap,npcxw)
            ){

                var rhdetail = _RHM.getRhNmb(npcconf.npcxw,npcxw,tjmap,key);
                if(rhdetail!=null)
                result.push({role:key,detail:rhdetail});
                /*
                if(rhdetail){
                    var rhnmb = rhdetail.rhnmb;
                    if(resultrhnmb==-1){
                        resultrhnmb = rhnmb;
                        resultRole=key;
                        resultDetail=rhdetail;
                    }else if(rhnmb<resultrhnmb){
                        resultrhnmb = rhnmb;
                        resultRole=key;
                        resultDetail=rhdetail;
                    }
                }*/
            }
        }

        //return {role:resultRole,detail:resultDetail};

        result.sort((a,b)=>{
            return a.detail.rhnmb-b.detail.rhnmb;
        });

        return result;

    },

    getUnLockedNmb:function(race){
        var nmb = 0;
        for(var i=0;i<window.gameData.playerTeamBack.length;i++){
            var roleinfo =window.gameData.playerTeamBack[i];
            var rolerace = _NPC[roleinfo.npctype]?_NPC[roleinfo.npctype].race:null;
            if(!roleinfo.locked
                &&(
                    race=="mo"
                    ||rolerace==race
                )
            ){
                nmb++;
            }
        }
        return nmb;
    },

    //获取最高属性值
    getMaxRhAttr:function(role){

        var arr = [];
        arr.push({type:"hlv",value:role.hlv});
        arr.push({type:"ilv",value:role.ilv});
        arr.push({type:"dlv",value:role.dlv});
        arr.push({type:"mlv",value:role.mlv});
        arr.push({type:"plv",value:role.plv});

        arr.sort((a,b)=>{
            return b.value-a.value;
        });

        return arr[0];
    },

    //获取最高修为值
    getMaxXwOfRole:function(role){

        if(role.xwlevel){
            return _RHM.getMaxXwObj(role.xwlevel); 
        }else{
            if(_NPC[role.npctype]){
                return _RHM.getMaxXwObj(_NPC[role.npctype].npcxw); 
            }
        }   
        return null;
    },

    //一键融合
    rhAll:function(targetrole){
        var npcconfig = _NPC[targetrole.npctype];
        var race =  npcconfig?npcconfig.race:null
        if(!targetrole.xwlevel){
            if(npcconfig)
                targetrole.xwlevel=_CU.cloneObj(npcconfig.npcxw);
            else
                targetrole.xwlevel={};
        }
        console.log(targetrole);
        var rhdnmb = _GAMEDATAHELPER.getGoodsNmb(window.gameData.specilItem,"融合丹");
        var playernmb = _RHM.getUnLockedNmb(race);
        var realrhnmb = rhdnmb>playernmb?playernmb:rhdnmb;
        var cutnmb = 0;

        var xwArr = [];
        var attrArr = [];

        _GAMEDATAHELPER.reduceSomeItemByName('融合丹',realrhnmb);

        for(var i=0;i<window.gameData.playerTeamBack.length;){
            if(cutnmb<realrhnmb){
                var roleinfo =window.gameData.playerTeamBack[i];
                var rolerace = _NPC[roleinfo.npctype]?_NPC[roleinfo.npctype].race:null;
                if(!roleinfo.locked
                    &&(
                        race=="mo"
                        ||rolerace==race
                    )
                ){
                    cutnmb++;
                    //console.log('融合:',roleinfo,cutnmb);
                    xwArr.push(_RHM.getMaxXwOfRole(roleinfo));
                    attrArr.push(_RHM.getMaxRhAttr(roleinfo));
                    window.gameData.playerTeamBack.splice(i,1);
                }else{
                    //console.log('无法融合:',roleinfo,cutnmb);
                    i++;
                }
            }else{
                break;
            }
        }

        for(var i=0;i<xwArr.length;i++){

            var xwObj = xwArr[i];
            if(xwObj&&xwObj.xw&&xwObj.level){
                var xw = xwObj.xw;
                var level = xwObj.level;

                if(!targetrole.xwlevel[xw]){
                    targetrole.xwlevel[xw]=level;
                    targetrole.xw[xw]=0;
                }else{
                    if(_RHM.comparaLevel(level,targetrole.xwlevel[xw])){
                        targetrole.xwlevel[xw]=level;
                    }
                }
            }
        }

        attrArr.sort((a,b)=>{
           return a.value-b.value;
        });
        for(var i=0;i<attrArr.length;i++){
            var type = attrArr[i].type;
            var value = attrArr[i].value;;
            var old = targetrole[type];
            var addattr = 0;
            if(addattr>old){
                addattr= Math.floor(old/10);
            }else{
                addattr = Math.floor(value/10);
            }
            targetrole[type]+=addattr;
        }


        _TIPS.showMessage('融合成功!(共融合'+realrhnmb+'次)');
        _MRDL.refreshPage();

    }

}